import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {MessageUtilService} from "great-zorroutils";
import {ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
import {Observable} from "rxjs";

@Component({
  selector: 'app-form-form-leave2',
  templateUrl: './form-leave2.component.html',
})
export class FormFormLeave2Component implements OnInit {

  formGrop: FormGroup;

  constructor(
    private fb: FormBuilder,
    private messageService: MessageUtilService,
  ) {
    this.formGrop = this.fb.group({
      userName: ['', [Validators.required]],
      email: ['', [Validators.email, Validators.required]],
      password: ['', [Validators.required]],
      confirm: ['',],
      comment: ['', [Validators.required]]
    });
  }

  ngOnInit() {
  }

  canDeactivate(
    component?: any,
    currentRoute?: ActivatedRouteSnapshot,
    currentState?: RouterStateSnapshot,
    nextState?: RouterStateSnapshot): Observable<boolean> | boolean {
    if (this.formGrop.dirty) {
      return this.messageService.canDeactivate(
        (saveCallback) => { // 点击离开并保存执行的回调
          // 调用后台保存接口
          // 后台接口返回后
          // 如果后台保存成功则执行：saveCallback(true);
          // 如果后台保存失败则执行：saveCallback(false);
          this.messageService.loading('正在调用后台接口保存，保存成功后将会离开！')
          setTimeout(()=>{
            saveCallback(true);
          }, 3000)
        },
        () => { // 点击取消按钮需要执行的回调（可选参数）
        }
      );
    } else {
      return true;
    }
  }

}
